﻿using System.Threading;
using System.Threading.Tasks;
using ESRI.ArcGIS.Client.Tasks;

namespace ESRI.ArcGIS.Client.Async
{
    public static partial class UploadTaskExtensions
    {
        #region DeleteTaskAsync

        /// <summary>
        /// Deletes the uploaded item from server.
        /// </summary>
        /// <param name="task"></param>
        /// <param name="itemID">The item ID.</param>
        /// <returns></returns>
        public static Task<DeleteTaskResult> DeleteTaskAsync(this UploadTask task,
            string itemID)
        {
            return DeleteTaskAsync(task, itemID, CancellationToken.None);
        }

        /// <summary>
        /// Deletes the uploaded item from server.
        /// </summary>
        /// <param name="task"></param>
        /// <param name="itemID">The item ID.</param>
        /// <param name="cancellationToken">Cancellation token for cancelling task.</param>
        /// <returns></returns>
        public static Task<DeleteTaskResult> DeleteTaskAsync(this UploadTask task,
            string itemID, CancellationToken cancellationToken)
        {
            return task.HandleTask<UploadTask, DeleteEventArgs, DeleteTaskResult>(
                t => t.DeleteAsync(itemID),
                (t, e) => t.DeleteCompleted += e,
                (t, e) => t.DeleteCompleted -= e,
                e => new DeleteTaskResult(e),
                cancellationToken);
        }

        #endregion

        #region UploadTaskAsync

        /// <summary>
        /// Uploads the file to server.
        /// </summary>
        /// <param name="task"></param>
        /// <param name="parameters">The upload parameters.</param>
        /// <returns></returns>
        public static Task<UploadTaskResult> UploadTaskAsync(this UploadTask task,
            UploadParameters parameters)
        {
            return UploadTaskAsync(task, parameters, CancellationToken.None);
        }

        /// <summary>
        /// Uploads the file to server.
        /// </summary>
        /// <param name="task"></param>
        /// <param name="parameters">The upload parameters.</param>
        /// <param name="cancellationToken">Cancellation token for cancelling task.</param>
        /// <returns></returns>
        public static Task<UploadTaskResult> UploadTaskAsync(this UploadTask task,
            UploadParameters parameters, CancellationToken cancellationToken)
        {
            return task.HandleTask<UploadTask, UploadEventArgs, UploadTaskResult>(
                t => t.UploadAsync(parameters),
                (t, e) => t.UploadCompleted += e,
                (t, e) => t.UploadCompleted -= e,
                e => new UploadTaskResult(e),
                cancellationToken);
        }

        #endregion
    }
}


